package com.project.email.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 监听器：监听email.queue队列中的消息
 */
@Component
@Slf4j
public class EmailListener {

    private final JavaMailSender javaMailSender;

    @Autowired
    public EmailListener(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * 发送邮件服务方法，监听RabbitMQ邮件队列并处理邮件发送请求
     *
     * @param emailData 邮件数据Map，包含发件人、收件人、主题和内容等信息
     *                  from: 发件人邮箱地址
     *                  to: 收件人邮箱地址
     *                  subject: 邮件主题
     *                  content: 邮件内容
     */
    @RabbitListener(queues = "email.queue")
    public void sendEmail(Map<String, String> emailData) {

        log.info("监听到邮件队列，开始发送邮件，数据：{}", emailData);

        // 获取邮件信息
        String from = emailData.get("from");
        String to = emailData.get("to");
        String subject = emailData.get("subject");
        String content = emailData.get("content");
        // 打印上面的信息
        log.info("from：{}, to：{}, subject：{}, content：{}", from, to, subject, content);

        // 构造并发送邮件
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setFrom(from); //发件箱
        mail.setTo(to);     //收件箱
        mail.setSubject(subject); //邮件主题
        mail.setText(content);    //生成的验证码
        javaMailSender.send(mail);
    }

}
